package com.byyy.ccts.modules.sys.controller;

import com.alibaba.fastjson.JSONArray;
import com.byyy.ccts.core.common.controller.BaseCRUDController;
import com.byyy.ccts.core.model.AjaxJson;
import com.byyy.ccts.core.query.data.Queryable;
import com.byyy.ccts.core.query.wrapper.EntityWrapper;
import com.byyy.ccts.core.security.shiro.authz.annotation.RequiresPathPermission;
import com.byyy.ccts.core.utils.JeewebPropertiesUtil;
import com.byyy.ccts.core.utils.MyBeanUtils;
import com.byyy.ccts.core.utils.StringUtils;
import com.byyy.ccts.modules.sys.entity.*;
import com.byyy.ccts.modules.sys.security.shiro.web.filter.authc.credential.RetryLimitHashedCredentialsMatcher;
import com.byyy.ccts.modules.sys.service.*;
import com.byyy.ccts.modules.sys.utils.UserUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;

/**
 * 
 * All rights Reserved, Designed By www.jeeweb.cn
 * 
 * @title: UserController.java
 * @package cn.jeeweb.modules.sys.controller
 * @description: 用户操作控制器
 * @author: 王存见
 * @date: 2017年5月25日 上午9:52:20
 * @version V1.0
 * @copyright: 2017 www.jeeweb.cn Inc. All rights reserved.
 *
 */
@Controller
@RequestMapping("${admin.url.prefix}/sys/user")
@RequiresPathPermission("sys:user")
public class UserController extends BaseCRUDController<User, String> {
	@Autowired
	private IUserService userService;

	@Autowired
	private IUserRoleService userRoleService;

	@Autowired
	private IRoleService roleService;
	@Autowired
	private IOrganizationService organizationService;
	@Autowired
	private IUserOrganizationService userOrganizationService;
	@Autowired
	private RetryLimitHashedCredentialsMatcher retryLimitHashedCredentialsMatcher;
	@Autowired
	private IDictService dictService;
	@Autowired
	private IUserDataPermissionService userDataPermissionService;

	public UserController() {
		setCommonService(userService);
	}

	@Override
	public String showCreate(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
		return display("create");
	}

	@RequestMapping(value = "{id}/changePassword", method = RequestMethod.GET)
	public String changePassword(@PathVariable("id") String id, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		User user = userService.selectById(id);
		model.addAttribute("data", user);
		return display("changePassword");
	}

	@RequestMapping(value = "{id}/changePassword", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson changePassword(@PathVariable("id") String id, HttpServletRequest request,
			HttpServletResponse response) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("密码修改成功");
		String password = request.getParameter("password");
		String regex = "^(?!([a-zA-Z]+|\\d+)$)[a-zA-Z\\d]{8,20}$";
		if (password == null || !password.matches(regex)) {
			ajaxJson.fail("密码不符合要求【至少8位,包含字母和数字，不包含特殊字符】！");
			return ajaxJson;
		}

		userService.changePassword(id, password);
		return ajaxJson;
	}

	@RequestMapping(value = "{id}/avatar", method = RequestMethod.GET)
	public String avatar(@PathVariable("id") String id, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		User user = userService.selectById(id);
		model.addAttribute("data", user);
		return display("avatar");
	}

	@RequestMapping(value = "{id}/avatar", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson avatar(User user, HttpServletRequest request, HttpServletResponse response) throws Exception {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("头像修改成功");
		User oldUser = commonService.selectById(user.getId());
		MyBeanUtils.copyBeanNotNull2Bean(user, oldUser);
		commonService.insertOrUpdate(oldUser);
		String currentUserId = UserUtils.getUser().getId();
		if (currentUserId.equals(user.getId())) {
			UserUtils.clearCache();
		}
		return ajaxJson;
	}

	@Override
	public void preEdit(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
		// 查询所有的角色List
		List<Role> allRoles = roleService.selectList(new EntityWrapper<Role>());
		request.setAttribute("allRoles", allRoles);
		if (!StringUtils.isEmpty(user.getId())) {
			// 查找关联角色
			List<Role> userRoles = roleService.findListByUserId(user.getId());
			request.setAttribute("roleIdList", userRoles);
			List<Organization> organizations = organizationService.findListByUserId(user.getId());
			String organizationIds = "";
			String organizationNames = "";
			for (Organization organization : organizations) {
				if (!StringUtils.isEmpty(organizationIds)) {
					organizationIds += ",";
					organizationNames += ",";
				}
				String organizationId = organization.getId();
				organizationIds += organizationId;
				organizationNames += organization.getName();

			}
			request.setAttribute("organizationIds", organizationIds);
			request.setAttribute("organizationNames", organizationNames);
		}
	}

	@Override
	public void preAjaxList(Queryable queryable,EntityWrapper<User> entityWrapper,HttpServletRequest request,
			HttpServletResponse response) {
		// 子查询
		String organizationid = request.getParameter("organizationid");
		if (!StringUtils.isEmpty(organizationid)) {
			entityWrapper.eq("uo.organization_id", organizationid);
		}
	}

	@Override
	public void preSave(User entity, HttpServletRequest request, HttpServletResponse response) {
		if (StringUtils.isEmpty(entity.getId())) {
			String password = entity.getPassword();
			String regex = "^(?!([a-zA-Z]+|\\d+)$)[a-zA-Z\\d]{8,20}$";
			if (password == null || !password.matches(regex)) {
				throw new RuntimeException("密码不符合要求【至少8位,包含字母和数字，不包含特殊字符】！");
			}
		}
		if (StringUtils.isEmpty(entity.getPortrait())) {
			entity.setPortrait(JeewebPropertiesUtil.getConfig("default.portrait"));
		}
	}

	@Override
	public void afterSave(User entity, HttpServletRequest request, HttpServletResponse response) {
		// 删除角色关联
		String[] roleIdList = request.getParameterValues("roleIdList");
		if (roleIdList != null && roleIdList.length > 0) {
			userRoleService.delete(new EntityWrapper<UserRole>(UserRole.class).eq("userId", entity.getId()));
			List<UserRole> userRoleList = new ArrayList<UserRole>();
			for (String roleid : roleIdList) {
				UserRole userRole = new UserRole();
				userRole.setUserId(entity.getId());
				userRole.setRoleId(roleid);
				userRoleList.add(userRole);
			}
			userRoleService.insertBatch(userRoleList);
		}

		// 删除部门关联
		String organizationIdListStr = request.getParameter("organizationIds");
		if (StringUtils.isNotEmpty(organizationIdListStr)) {
			String[] organizationIdList = organizationIdListStr.split(",");
			if (organizationIdList != null && organizationIdList.length > 0) {
				userOrganizationService.delete(new EntityWrapper<UserOrganization>(UserOrganization.class).eq("userId", entity.getId()));
				List<UserOrganization> userOrganizationList = new ArrayList<UserOrganization>();
				for (String organizationId : organizationIdList) {
					UserOrganization userOrganization = new UserOrganization();
					userOrganization.setUserId(entity.getId());
					userOrganization.setOrganizationId(organizationId);
					userOrganizationList.add(userOrganization);
				}
				userOrganizationService.insertBatch(userOrganizationList);
			}
		}
	}

	@RequestMapping(value = "info", method = RequestMethod.GET)
	public String info(@RequestParam(required = false) String id, Model model, HttpServletRequest request,
			HttpServletResponse response) {
		User user = userService.selectById(id);
		model.addAttribute("data", user);
		return display("info");
	}

	/**
	 * 锁定/解锁用户
	 * @return
	 */
	@RequestMapping(value = "/lockOrUnlock", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson lockOrUnlock(String id, String status) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("更新完毕");
		User user = this.userService.selectById(id);
		user.setStatus(status);
		this.userService.updateById(user);
		if (User.STATUS_NORMAL.equals(status)) {
			retryLimitHashedCredentialsMatcher.clear(user.getUsername());
		}
		return ajaxJson;
	}

	/**
	 * 角色数据权限页面
	 * @param user
	 * @param model
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "dataPermission", method = RequestMethod.GET)
	public String dataPermission(User user, Model model, HttpServletRequest request, HttpServletResponse response) {
		List<Dict> dataPermissions = dictService.selectDataPermissionTreeList();
		List<Dict> selectDataPermissions = dictService.findDataPermissionByUserId(user.getId());
		model.addAttribute("dataPermissions", JSONArray.toJSON(dataPermissions));
		model.addAttribute("selectDataPermissions", JSONArray.toJSON(selectDataPermissions));
		model.addAttribute("data", user);
		return display("dataPermission");
	}

	/**
	 * 角色数据权限设置
	 * @param user
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value = "/doDataPermission", method = RequestMethod.POST)
	@ResponseBody
	public AjaxJson doDataPermission(User user, HttpServletRequest request, HttpServletResponse response) {
		AjaxJson ajaxJson = new AjaxJson();
		ajaxJson.success("数据权限设置成功");
		String userId = user.getId();
		// 删除菜单关联
		userDataPermissionService.delete(new EntityWrapper<UserDataPermission>(UserDataPermission.class).eq("userId", userId));
		String selectDataPermission = request.getParameter("selectDataPermissions");
		String[] selectDataPermissions = selectDataPermission.split(",");
		List<UserDataPermission> userDataPermissionList = new ArrayList<UserDataPermission>();
		UserDataPermission roleDataPermission = null;
		for (String dataPermissionId : selectDataPermissions) {
			roleDataPermission = new UserDataPermission();
			roleDataPermission.setUserId(userId);
			roleDataPermission.setDatapermissionId(dataPermissionId);
			userDataPermissionList.add(roleDataPermission);
		}
		userDataPermissionService.insertOrUpdateBatch(userDataPermissionList);
		UserUtils.clearCache();
		return ajaxJson;
	}

}